package com.javatip.project.deep_learning.trainMission.controller;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.github.pagehelper.PageInfo;
import com.javatip.common.utils.Utils;
import com.javatip.project.deep_learning.app01Dataset.domain.App01Dataset;
import com.javatip.project.deep_learning.app01Dataset.service.App01DatasetServiceImpl;
import com.javatip.project.deep_learning.app01Dataset.service.IApp01DatasetService;
import com.javatip.project.deep_learning.model.domain.Model;
import com.javatip.project.deep_learning.model.service.IModelService;
import com.javatip.project.queue.domain.Task;
import com.javatip.project.queue.service.QueueService;
import com.javatip.project.system.user.domain.User;
import com.javatip.project.system.user.service.IUserService;
import io.swagger.annotations.Api;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.util.ThreadContext;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.javatip.project.deep_learning.trainMission.domain.TrainMission;
import com.javatip.project.deep_learning.trainMission.service.ITrainMissionService;
import com.javatip.framework.web.controller.BaseController;
import com.javatip.framework.web.page.TableDataInfo;
import com.javatip.framework.web.domain.AjaxResult;
import org.apache.commons.codec.binary.Base64;   //用于base64编码

/**
 * 训练任务信息操作处理
 *
 * @author 袁伟
 * @date 2024-07-12
 */
//  可以添加拷贝别人的训练任务的功能，创建训练任务时，根据模型对图像进行处理，防止不匹配

@Api(tags = "语义分割训练任务管理")
@Controller
@RequestMapping("/deep_learning/trainMission")
public class TrainMissionController extends BaseController {
    @Autowired
    private QueueService queueService;
    private String prefix = "deep_learning/trainMission";
    @Autowired
    private ITrainMissionService trainMissionService;

    @Autowired
    private IModelService modelService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IApp01DatasetService iApp01DatasetService;
    @Autowired
    private App01DatasetServiceImpl app01DatasetServiceImpl;

    @RequiresPermissions("deep_learning:trainMission:view")
    @GetMapping()
    public String trainMission() {
        return prefix + "/trainMission";
    }

    // 每 10 秒调用一次 doTrain 方法
//    @Scheduled(fixedRate = 10000)
    public void scheduledDoTrain() {
//        System.out.println("scheduledDoTrain()");
        try {
            DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
            ThreadContext.bind(manager);
            doTraining();
        } catch (Exception e) {
            System.out.println("出错");
        }
    }


    /**
     * 查询训练任务列表
     */
    @RequiresPermissions("deep_learning:trainMission:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(TrainMission trainMission) {
        startPage();
        List<TrainMission> list = trainMissionService.selectTrainMissionList(trainMission);
        for (TrainMission mission : list) {
            String userName = userService.getUsernameByUserId(Long.valueOf(mission.getUserId()));
//            System.out.println("TrainMissionController.java:userName="+userName);
            mission.setUserName(userName);
//            System.out.println(mission.toString());
        }

//        System.out.println(list.toArray().length);
        System.out.println("list" + list);
        return getDataTable(list);
    }

    /**
     * get方式查询训练任务列表，以List形式返回
     */
    @GetMapping("/getList")
    @ResponseBody
    public List<TrainMission> getList(TrainMission trainMission) {
        startPage();
        return trainMissionService.selectTrainMissionList(trainMission);
    }


    /**
     * 新增训练任务
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存训练任务
     */
    @RequiresPermissions("deep_learning:trainMission:add")
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(TrainMission trainMission) {
//        System.out.println("trainMission"+trainMission.toString());

        return toAjax(trainMissionService.insertTrainMission(trainMission));
    }

    /**
     * 修改训练任务
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Integer id, ModelMap mmap) {
        TrainMission trainMission = trainMissionService.selectTrainMissionById(id);
        mmap.put("trainMission", trainMission);

        return prefix + "/edit";
    }

    /**
     * 修改保存训练任务
     */
    @RequiresPermissions("deep_learning:trainMission:edit")
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(TrainMission trainMission) {
        return toAjax(trainMissionService.updateTrainMission(trainMission));
    }

    /**
     * 删除训练任务
     */
    @RequiresPermissions("deep_learning:trainMission:remove")
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(trainMissionService.deleteTrainMissionByIds(ids));
    }

    /**
     * 走数据库查模型名称和模型归属用户的名称，并返回，供前端选择
     * 已经做了归属用户的筛选，所以不需要再做筛选
     */
    @GetMapping("selectModelAndUser")
    @ResponseBody
    public List<String> selectModelAndUser() {
        Model model = null;
        // 获取当前登录用户的id
        Integer currentUserId = Math.toIntExact(getUserId());
        List<Model> tmpResult = modelService.selectModelList(model);
        List<Model> result = new ArrayList<>();
//		筛选出isPublic为1或者归属当前用户的模型，加入到新的list中，供前端选择
//		System.out.println(tmpResult);
        for (Model m : tmpResult) {
            if (m.getIsPublic() == 1 || m.getUserId() == currentUserId) {
                model = m;
                result.add(model);
            }
        }
//		根据每个模型的归属用户的id，从用户表查询用户的名称，并创建新的对象，将模型名称、模型id，和用户id，用户名称一起返回
//		创建新的对象，将模型名称和用户id，用户名称一起返回
        List<String> resultList = new ArrayList<>();
        for (Model m : result) {
            User user = userService.selectUserById(Long.valueOf(m.getUserId()));

            resultList.add(
                    m.getId() + "|"
                            + m.getModelName() + "|"
                            + m.getUserId() + "|"
                            + user.getUserName()
                            + "|" + m.getIsWeight()
            );
        }
//		System.out.println(resultList);
        return resultList;
    }

    /**
     * 走数据库查数据集名称，id，和数据集归属用户的名称，id，供前端选择
     * 已经做了归属用户的筛选，所以不需要再做筛选
     */
    @GetMapping("selectDatasetAndUser")
    @ResponseBody
    public List<String> selectDatasetAndUser() {
        App01Dataset app01Dataset = null;
        // 获取当前登录用户的id
        Integer currentUserId = Math.toIntExact(getUserId());
//        System.out.println("currentUserId="+    currentUserId);
        List<App01Dataset> tmpResult = iApp01DatasetService.selectApp01DatasetList(app01Dataset);
        List<App01Dataset> result = new ArrayList<>();
//		System.out.println(tmpResult);
        for (App01Dataset a : tmpResult) {
            if ((a.getIsPublic() == 1 || a.getUserId().intValue() == currentUserId) && a.getNumVall() != 0) {
                result.add(a);
            }
        }
        System.out.println(result.size());
//		根据每个模型的归属用户的id，从用户表查询用户的名称，并创建新的对象，将模型名称、模型id，和用户id，用户名称一起返回
//		创建新的对象，将模型名称和用户id，用户名称一起返回
        List<String> resultList = new ArrayList<>();
        for (App01Dataset m : result) {
            User user = userService.selectUserById(Long.valueOf(m.getUserId()));

            resultList.add(m.getId() + "|" + m.getName() + "|" + m.getUserId() + "|" + user.getUserName());
        }
        System.out.println(resultList);
        return resultList;
    }

    //可以选取没有label的数据集进行识别
    @GetMapping("selectDatasetAndUserNoAboutLabel")
    @ResponseBody
    public List<String> selectDatasetAndUserNoAboutLabel() {
        App01Dataset app01Dataset = null;
        // 获取当前登录用户的id
        Integer currentUserId = Math.toIntExact(getUserId());
        List<App01Dataset> tmpResult = iApp01DatasetService.selectApp01DatasetList(app01Dataset);
        List<App01Dataset> result = new ArrayList<>();
//		System.out.println(tmpResult);
        for (App01Dataset a : tmpResult) {
            if (a.getIsPublic() == 1 || a.getUserId().intValue() == currentUserId) {
                app01Dataset = a;
                result.add(app01Dataset);
            }
        }
//		根据每个模型的归属用户的id，从用户表查询用户的名称，并创建新的对象，将模型名称、模型id，和用户id，用户名称一起返回
//		创建新的对象，将模型名称和用户id，用户名称一起返回
        List<String> resultList = new ArrayList<>();
        for (App01Dataset m : result) {
            User user = userService.selectUserById(Long.valueOf(m.getUserId()));

            resultList.add(m.getId() + "|" + m.getName() + "|" + m.getUserId() + "|" + user.getUserName());
        }
//		System.out.println(resultList);
        return resultList;
    }

    /**
     * 查询训练任务列表，只要和当前登录用户有关以及公开的的训练任务
     */
    @RequiresPermissions("deep_learning:trainMission:list")
    @PostMapping("/listWithUserOrPublic")
    @ResponseBody
    public TableDataInfo listWithUserOrPublic(TrainMission trainMission) {
        startPage();
        // 获取当前登录用户的id
        Integer currentUserId = Math.toIntExact(getUserId());
        System.out.println("TrainMissionContorller---------/listWithUserOrPublic");
        List<TrainMission> list = trainMissionService.selectTrainMissionListWithUserOrPublic(currentUserId,trainMission);

//        添加用户名
        for (TrainMission m : list) {
            String userName = userService.getUsernameByUserId(Long.valueOf(m.getUserId()));
            m.setUserName(userName);
        }
        return getDataTable(list);
    }

    /**
     * 查询训练任务列表，只要和当前登录用户有关的训练任务
     */
    @RequiresPermissions("deep_learning:trainMission:list")
    @PostMapping("/listWithUser")
    @ResponseBody
    public TableDataInfo listWithUser(TrainMission trainMission) {
        startPage();  // 启动分页
        System.out.println("TrainMissionController---------/listWithUser");
// 获取当前登录用户的id
        int currentUserId = Math.toIntExact(getUserId());

        // 获取当前用户的训练任务列表，直接通过 mapper 筛选
        List<TrainMission> list = trainMissionService.selectTrainMissionListByUser(currentUserId, trainMission);


        System.out.println("当前用户id：" + currentUserId);
        System.out.println("list: " + list);

        // 给每个符合条件的训练任务添加用户名
        for (TrainMission m : list) {
            m.setUserName(userService.getUsernameByUserId(Long.valueOf(m.getUserId())));

            //设置数据集的归属用户
            App01Dataset dataSet=app01DatasetServiceImpl.selectApp01DatasetById(m.getDatasetTrainId());
            m.setDatasetTrain((m.getDatasetTrain()+"："+userService.getUsernameByUserId(dataSet.getUserId().longValue())));

            dataSet=app01DatasetServiceImpl.selectApp01DatasetById(m.getDatasetValId());
            m.setDatasetVal((m.getDatasetVal()+"："+userService.getUsernameByUserId(dataSet.getUserId().longValue())));
        }



        return getDataTable(list);  // 返回过滤后的list
    }


    // 定义一个标准化的错误响应类
    static class ErrorResponse {
        private String message;

        public ErrorResponse(String message) {
            this.message = message;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }
    }

    /**
     * 开始单个训练任务
     *
     * @param id
     * @return
     */
    @GetMapping("doSingleTraining/{id}")
    public ResponseEntity<String> doSingleTraining(@PathVariable("id") int id) {
        int result = trainMissionService.startSingleTraining(id);

        if (result == 0) {
            //压入队列=================
            Task task= new Task(trainMissionService.selectTrainMissionById(id).getTrainMissionName(),"segTrain",id, new Timestamp(System.currentTimeMillis()));
            String res=queueService.saveTask(task);

            return ResponseEntity.ok("Training started successfully for id: " + id);
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Failed to start training for id: " + id);
        }
    }


    /**
     * 停止单个训练任务
     *
     * @param id
     * @return
     */
    @GetMapping("stopSingleTraining/{id}")
    public ResponseEntity<String> stopSingleTraining(@PathVariable("id") int id) {
        System.out.println("stopSingleTraining");
        boolean isTrainingStopped = trainMissionService.stopSingleTraining(id);

        if (isTrainingStopped) {
            //删除队列
            queueService.deleteTaskByTypeAndID("segTrain", id);

            System.out.println("Training stopped successfully for id: " + id);
            return ResponseEntity.ok("Training stopped successfully for id: " + id);
        } else {
            System.out.println("Failed to stop training for id: " + id);
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Failed to stop training for id: " + id);
        }
    }

    /**
     * 获取训练结果
     *
     * @param id
     * @return
     */
    @GetMapping("/trainingResult/{id}")
    @ResponseBody
    public Map<String, Object> getTrainingResult(@PathVariable("id") int id) {
        String currentPath = System.getProperty("user.dir");
        currentPath = currentPath + "/src/main/resources/trainResult/" + id + "/predictResult/" + "评价指标.txt";

        Map<String, Object> response = new HashMap<>();
        try {
            // 读取文件内容
            String content = new String(Files.readAllBytes(Paths.get(currentPath)));

            // 读取图片，和评价指标.txt文件在同一目录下，图片名为trainResult.png
            String imagePath = currentPath.replace("评价指标.txt", "trainResult.png");
            byte[] imageBytes = Files.readAllBytes(Paths.get(imagePath));

            // 将图片数据编码为 Base64
            String base64Image = Base64.encodeBase64String(imageBytes);


            // 使用正则表达式解析文件内容
            Pattern pattern = Pattern.compile("epoch=(\\d+)[\\s\\S]*?mIoU:(\\d+\\.\\d+)[\\s\\S]*?F1-score:(\\d+\\.\\d+)[\\s\\S]*?accuracy:(\\d+\\.\\d+)[\\s\\S]*?loss:(\\d+\\.\\d+)");
            Matcher matcher = pattern.matcher(content);

            // 初始化最大mIoU值和对应的数据
            double maxMIoU = -1;
            String maxEpochData = "";
            String previousEpochData = "";
            String nextEpochData = "";
            String currentEpochData = "";

            while (matcher.find()) {
                int epoch = Integer.parseInt(matcher.group(1));
                double mIoU = Double.parseDouble(matcher.group(2));
                String f1Score = matcher.group(3);
                String accuracy = matcher.group(4);
                String loss = matcher.group(5);

                currentEpochData = String.format("epoch=%d\nmIoU:%.1f\nF1-score:%s\naccuracy:%s\nloss:%s\n",
                        epoch, mIoU, f1Score, accuracy, loss);

                if (mIoU > maxMIoU) {
                    maxMIoU = mIoU;
                    maxEpochData = currentEpochData;
                } else {
                    previousEpochData = currentEpochData;
                }
            }

            // 获取最大mIoU值的前后epoch数据
            if (!maxEpochData.isEmpty()) {
                response.put("maxEpochData", maxEpochData);
                response.put("previousEpochData", previousEpochData);
                response.put("nextEpochData", nextEpochData);
            }
            response.put("image", base64Image);
            response.put("status", "success");
            response.put("data", content);
        } catch (IOException e) {
            response.put("status", "error");
            response.put("message", "暂未生成训练结果，请耐心等待。");
//            response.put("message", "Failed to read the file: " + e.getMessage());
        }
        return response;
    }

    /**
     * 获取训练任务状态
     *
     * @param id
     * @return
     */
    @GetMapping("/getStatus/{id}")
    public ResponseEntity<TrainMission> getTrainMissionStatus(@PathVariable("id") int id) {
        TrainMission trainMission = trainMissionService.selectTrainMissionById(id);

        if (trainMission != null) {
            return ResponseEntity.ok(trainMission);
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }
    }

    /**
     * 修改训练任务的status为待训练
     *
     * @param id
     * @return
     */
    @GetMapping("/updateStatusToWait/{id}")
    public ResponseEntity<String> updateStatusToWait(@PathVariable("id") int id) {
        System.out.println("updateStatusToWait");
        int result = trainMissionService.updateStatusToWait(id);
//        // 在数据库表中更新识别任务的加入队列时间
        trainMissionService.setTimeToQueue(id);
//
        if (result == 1 ) {
            //压入队列=================
            Task task= new Task(trainMissionService.selectTrainMissionById(id).getTrainMissionName(),"segTrain",id, new Timestamp(System.currentTimeMillis()));
            String res=queueService.saveTask(task);
            return ResponseEntity.ok("Status updated successfully for id: " + id);
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Failed to update status for id: " + id);
        }
    }

    /**
     * 修改训练任务的status为未训练
     *
     * @param id
     * @return
     */
    @GetMapping("/updateStatusToNotTrain/{id}")
    public ResponseEntity<String> updateStatusToNotTrain(@PathVariable("id") int id) {
        System.out.println("updateStatusToNotTrain");

        int result = trainMissionService.updateStatusToNotTrain(id);


        if (result == 1 ) {
            //删除队列
            queueService.deleteTaskByTypeAndID("segTrain", id);

            return ResponseEntity.ok("Status updated successfully for id: " + id);
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Failed to update status for id: " + id);
        }
    }

    /**
     * 获取status为待训练和训练中的训练任务列表，返回数组
     *
     * @return
     */
    @GetMapping("/getWaitAndTrainingList")
    @ResponseBody
//	返回数组
    public List<Object[]> getWaitAndTrainingList() {
//        startPage();
        List<TrainMission> list = trainMissionService.selectWaitAndTrainingList();
//        System.out.println("list: " + list);
        // 构建数组
        List<Object[]> resultList = new ArrayList<>();
        for (TrainMission trainMission : list) {
//			附带每个列的名称

            Object[] obj = new Object[12];
            obj[0] = trainMission.getId();
            obj[1] = trainMission.getModel();
            obj[2] = trainMission.getDatasetTrain();
            obj[3] = trainMission.getDatasetVal();
            obj[4] = trainMission.getBatchSize();
            obj[5] = trainMission.getMinEpoch();
            obj[6] = trainMission.getMaxEpoch();
            obj[7] = trainMission.getStatus();
            obj[8] = trainMission.getEarlyStop();
            obj[9] = trainMission.getOpLr();
            obj[10] = trainMission.getUserId();
            obj[11] = userService.selectUserById(Long.valueOf(trainMission.getUserId())).getUserName();
            System.out.println("obj: " + obj);
            resultList.add(obj);
        }
        return resultList;
    }


    /**
     * 停止所有训练
     *
     * @return
     */
    @GetMapping("stopTraining")
//	@ResponseBody
    public ResponseEntity<?> stopTraining() {

        System.out.println("Controller-stopTraining");

        try {
            int result = trainMissionService.stopTraining(); // 获取结果

            if (result == 0) {
                // 成功的情况，返回 200 OK 和结果
                return ResponseEntity.ok().body("训练成功");
            } else {
                // 失败的情况，返回 400 错误响应
                System.out.println("Controller-未正常结束");
                return ResponseEntity.badRequest().body(new ErrorResponse("训练失败，请检查输入或稍后重试。"));
            }
        } catch (Exception e) {
            // 捕获并处理所有异常，返回自定义错误响应
            String errorMessage = "执行Python脚本时发生错误：" + e.getMessage();
            System.err.println(errorMessage);
            e.printStackTrace(); // 打印堆栈信息，帮助调试
            return ResponseEntity.badRequest().body(new ErrorResponse(errorMessage));
        }
    }

    /**
     * 如果为待训练任务，就只改变数据库的值就行了，如果是训练中任务，就需要调用接口停止训练
     */
    @GetMapping("updateStatus/{id}")
    @ResponseBody
    public ResponseEntity<String> updateStatus(@PathVariable("id") int id) {
        System.out.println("updateStatus");
        TrainMission trainMission = trainMissionService.selectTrainMissionById(id);
        if (trainMission.getStatus().equals("待训练")) {
            // 待训练任务，只改变数据库的值就行了
            int result = trainMissionService.updateStatusToNotTrain(id);
            System.out.println("result: " + result);
            if (result == 1) {
                return ResponseEntity.ok("Status updated successfully for id: " + id);
            } else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Failed to update status for id: " + id);
            }
        } else if (trainMission.getStatus().equals("训练中")) {
            // 训练中任务，需要调用接口停止训练
            System.out.println("Controller-updateStatus-停止训练");
            try {
                ResponseEntity<?> responseEntity = stopTraining();// 调用停止训练接口
                trainMissionService.updateStatusToNotTrain(id); // 更新数据库状态为未训练
                if (responseEntity.getStatusCode() == HttpStatus.OK) {
                    // 成功的情况，返回 200 OK 和结果
                    return ResponseEntity.ok("停止训练成功");
                } else {
                    // 失败的情况，返回 400 错误响应
                    System.out.println("Controller-updateStatus-未正常结束");
                    return ResponseEntity.badRequest().body(String.valueOf(new ErrorResponse("训练失败，请检查输入或稍后重试。")));
                }

            } catch (Exception e) {
                // 捕获并处理所有异常，返回自定义错误响应
                String errorMessage = "执行Python脚本时发生错误：" + e.getMessage();
                System.err.println(errorMessage);
                e.printStackTrace(); // 打印堆栈信息，帮助调试
                return ResponseEntity.badRequest().body(String.valueOf(new ErrorResponse(errorMessage)));
            }
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Failed to update status for id: " + id);

        }
    }

    /**
     * 训练列表里逐个训练
     *
     * @return
     */
    @GetMapping("doTrain")
//	@ResponseBody
    public ResponseEntity<?> doTraining() {

//        System.out.println("Controller-doTrain");

        try {
            int result = trainMissionService.doTrain(); // 获取结果

            if (result == 0) {
                // 成功的情况，返回 200 OK 和结果
                return ResponseEntity.ok().body("训练成功");
            } else {
                // 失败的情况，返回 400 错误响应
                System.out.println("Controller-未正常结束");
                return ResponseEntity.badRequest().body(new ErrorResponse("训练失败，请检查输入或稍后重试。"));
            }
        } catch (Exception e) {
            // 捕获并处理所有异常，返回自定义错误响应
            String errorMessage = "执行Python脚本时发生错误：" + e.getMessage();
            System.err.println(errorMessage);
            e.printStackTrace(); // 打印堆栈信息，帮助调试
            return ResponseEntity.badRequest().body(new ErrorResponse(errorMessage));
        }
    }


    // 获取所有已完成的训练任务列表,且和当前登录用户相关
    @PostMapping("/getFinishedList")
    @ResponseBody
    public TableDataInfo getFinishedList(TrainMission trainMission) {
//        startPage();
        List<TrainMission> list = trainMissionService.selectFinishedList(trainMission);
        // 获取当前登录用户的id
        Long currentUserId = getUserId();
        List<TrainMission> result = new ArrayList<>();
        for (TrainMission m : list) {
            if (m.getUserId() == Integer.valueOf(String.valueOf(currentUserId))) {
                result.add(m);
            }
        }
        System.out.println("result: " + result);
        return getDataTable(result);
    }

    // 获取所有已完成的训练任务列表,且和当前登录用户相关
    @GetMapping("/getFinishedTrainMissionList")
    @ResponseBody
    public List<TrainMission> getFinishedTrainMissionList(TrainMission trainMission) {
//        startPage();
        List<TrainMission> list = trainMissionService.selectFinishedList(trainMission);
        // 获取当前登录用户的id
        Long currentUserId = getUserId();
        List<TrainMission> result = new ArrayList<>();
        for (TrainMission m : list) {
            if (m.getUserId() == Integer.valueOf(String.valueOf(currentUserId)) || m.getIsPublic() == 1) {
                //        添加用户名
                m.setUserName(userService.selectUserById(Long.valueOf(m.getUserId())).getUserName());
                result.add(m);
            }
        }
//        System.out.println("result: " + result);
        return result;
    }


    //   url: `/deep_learning/trainMission/useForInference?id=${tmpId}&datasetId=${selectedDatasetId}`
    @GetMapping("/useForInference")
    @ResponseBody
    public ResponseEntity<String> useForInference(@RequestParam(value = "id", required = true) int tmpId,
                                                  @RequestParam(value = "datasetId", required = true) int selectedDatasetId) {
        System.out.println("useForInference");
        System.out.println("id: " + tmpId);
        System.out.println("datasetId: " + selectedDatasetId);
        App01Dataset app01Dataset = app01DatasetServiceImpl.selectApp01DatasetById(selectedDatasetId);

        String image_path = app01Dataset.getLocation();

        TrainMission trainMission = trainMissionService.selectTrainMissionById(tmpId);
        Model model = modelService.selectModelById(trainMission.getModelId());

        //获取当前路径
        String currentPath = System.getProperty("user.dir");
        String parentParentPath = Utils.getParentPath(currentPath, 0);
        currentPath = parentParentPath + "/src/main/resources/CorsicanFire/trainResult/" + tmpId + "/predictResult/";

        return null;
    }

    //	处理delete删除请求，删除训练任务对应文件夹
    @PostMapping("/delete/{id}")
    @ResponseBody
    public ResponseEntity<String> delete(@PathVariable("id") Integer id) {
        System.out.println("删除训练任务");
        int result = trainMissionService.deleteTrainMissionById(id);
        if (result == 1) {
            return ResponseEntity.ok("Delete started successfully for id: " + id);
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Failed to start deleting for id: " + id);
        }
    }

    /**
     * 获取进度条数据，getProgress+id
     */
    @GetMapping("/getProgress/{id}")
    @ResponseBody
    public Map<String, Object> getProgress(@PathVariable("id") int id) {
//        System.out.println("getProgress");
        Map<String, Object> response = new HashMap<>();
        TrainMission trainMission = trainMissionService.selectTrainMissionById(id);
        if (trainMission != null) {
            response.put("status", "success");
            // 获取当前路径
            String currentPath = System.getProperty("user.dir");
            String parentParentPath = Utils.getParentPath(currentPath, 0);
            currentPath = parentParentPath + "/src/main/resources/trainResult/" + id + "/predictResult/";

            // 读取 currentPath 下面的评价指标.txt 文件，如果不存在，则返回空数据
            String content = "";
            try {
                content = new String(Files.readAllBytes(Paths.get(currentPath + "评价指标.txt")));
            } catch (IOException e) {
//                e.printStackTrace();
                response.put("status", "success");
                response.put("data", "0.00");
//                System.out.println("txt文件不存在");
                response.put("message", "未开始训练");
                return response;
            }

            // 解析内容，找到 bestEpoch 和最后一个 epoch 的值
            String[] lines = content.split("\n");
            int lastEpochValue = 0;
            boolean bestEpochFound = false;
            boolean hasMoreLinesAfterBestEpoch = false;

//            for (String line : lines) {
//                if (line.startsWith("epoch=")) {
//                    String epochValueStr = line.substring("epoch=".length());
//
//                    try {
//                        lastEpochValue = Integer.parseInt(epochValueStr.trim());
////                        System.out.println("lastEpochValue: "+ lastEpochValue);
//                    } catch (NumberFormatException e) {
//                        e.printStackTrace();
//                    }
//                }
////                else if (line.startsWith("bestEpoch=")) {
////                    bestEpochFound = true;
////                    break;
////                }
//            }
            // 遍历每一行
            for (int i = 0; i < lines.length; i++) {
                String line = lines[i];

                if (line.startsWith("epoch=")) {
                    String epochValueStr = line.substring("epoch=".length()).trim();
                    try {
                        lastEpochValue = Integer.parseInt(epochValueStr);
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                } else if (line.startsWith("bestEpoch=")) {
                    bestEpochFound = true;
                    // 如果是最后一行，则表示没有更多行
                    if (i == lines.length - 1) {
                        hasMoreLinesAfterBestEpoch = false;
                    } else {
                        hasMoreLinesAfterBestEpoch = true;
                    }
                }
            }
            // 如果bestEpoch后没有更多行，返回进度100
            if (bestEpochFound && !hasMoreLinesAfterBestEpoch) {
                response.put("data", "100");
                return response;
            }


            // 返回进度数据
//            if (bestEpochFound) {
//                response.put("data", 100); // 表示进度为 100%
//            } else {
            // 假设每个 epoch 代表 10%，根据需要调整

//                System.out.println("maxEpoch"+trainMission.getMaxEpoch());
            double v = Double.parseDouble(String.valueOf(lastEpochValue));
            double v1 = Double.parseDouble(trainMission.getMaxEpoch().toString());

//                System.out.println(v/v1*100);
//                System.out.println("lastEpochValue / trainMission.getMaxEpoch()*100:"+lastEpochValue / trainMission.getMaxEpoch()*100);
            // 保留两位小数
            DecimalFormat df = new DecimalFormat("#.00");
            String str = df.format(v / v1 * 100);
            response.put("data", str);
//            }

            response.put("message", "获取进度条数据成功");
            return response;
        } else {
            response.put("status", "error");
            response.put("message", "获取进度条数据失败");
            return response;
        }
    }

    /**
     * 检查任务名称是否存在
     *
     * @param name
     * @return
     */
    @GetMapping("/checkTrainMissionName")
    @ResponseBody
    public ResponseEntity<Boolean> checkTrainMissionName(@RequestParam("name") String name) {
        int userId = getSysUser().getUserId().intValue();
        boolean exists = trainMissionService.isTrainMissionNameExists(name, userId); // 该方法检查任务名称是否存在
        return ResponseEntity.ok(exists);
    }


    /**
     * 获取队列位次
     */
    @GetMapping("/getQueuePosition/{id}")
    public ResponseEntity<Map<String, Object>> getQueuePosition(@PathVariable("id") Integer id) {
//        System.out.println("getQueuePosition");

        Integer postion =queueService.getTimePositionByTaskID(id,"segTrain");
        Map<String, Object> response = new HashMap<>();


        if (postion != null) {

                    response.put("queuePosition", postion);

        } else {
            response.put("queuePosition", null);
        }

        return ResponseEntity.ok(response);
    }
    


    @GetMapping("/getIsWeight/{id}")
    @ResponseBody
    public Map<String, Boolean> getIsWeight(@PathVariable("id") Integer id) {
//        System.out.println("getIsWeight");
        TrainMission trainMission = trainMissionService.selectTrainMissionById(id);
//        System.out.println("model.getIsWeight():"+model);
        Map<String, Boolean> response = new HashMap<>();
        response.put("isWeight", trainMission.getIsWeight());
        return response;
    }


    @GetMapping("/getExceptionLog/{id}")
    @ResponseBody
    public ResponseEntity<String> getExceptionLog(@PathVariable("id") int id) {
        System.out.println("getExceptionLog");
        // 根据训练任务 ID 获取日志文件路径
        //获取当前路径
        String currentPath = System.getProperty("user.dir");
        String parentParentPath = Utils.getParentPath(currentPath, 0);
        // 训练异常记录txt文件存储位置
        String exceptionRecordPath = parentParentPath + "/src/main/resources/trainResult" + "/" + id + "/exceptionRecord.txt";

        try {
            // 读取日志文件内容
            System.out.println("读取日志文件");
            String logContent = new String(Files.readAllBytes(Paths.get(exceptionRecordPath)), StandardCharsets.UTF_8);
//            读取logContent最后五行,正序排列
            String[] lines = logContent.split("\n");
            StringBuilder sb = new StringBuilder();
//            过滤包含UserWarning的行UserWarning: size_average and reduce args will be deprecated, please use reduction='mean' instead.
//  warnings.warn(warning.format(ret))
            for (int i = 0; i < lines.length; i++) {
                if (lines[i].contains("UserWarning: size_average and reduce args will be deprecated, please use reduction='mean' instead."
                )|| lines[i].contains("[00:00<?, ?it/s]")) {
                    continue;
                }
                sb.append(lines[i]).append("\n");
            }
            logContent = sb.toString();
            System.out.println("日志文件内容：\n" + logContent);
            return ResponseEntity.ok(logContent);
        } catch (IOException e) {
            System.err.println("读取日志文件失败");
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("读取日志文件失败");
        }
    }


}